import config from "../../utils/config.js";
  // pages/newcar/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ConsultationFlag:'none', //咨询模态框参数，block显示none隐藏
    classify:'',//当前选中分类，1排序，2品牌，3首付，4月供，5筛选
    cateList:[],//品牌数组
    screen:[],//筛选数据数组
    screenSelstorage:[],//选中数组集合存储
    screenSelall:[],//选中数组集合
    screenflag:0,//当前选中的筛选分类标记
    toview:'scroll5',//锚点定位，当前锚点id
    payment:[],//首付数据
    paymentflag: 0,//当前选中首付标记
    paymentname: '',//当前选中首付显示值
    paymentvalue: '',//当前选中首付值
    paymenttitle:'不限',//当前自定义显示金额
    paymentdiy:'',//首付自定义值
    monthpay: [],//月供数据
    monthpayflag: 0,//当前选中月供标记
    monthpayname: '',//当前选中月供显示值
    monthpayvalue: '',//当前选中月供值
    monthpaytitle: '不限',//当前月供显示值
    monthpaydiy: '',//月供自定义值
    keyword:'',//当前搜索关键字或品牌
    sort: 1,//当前排序，1默认，2销量最高，3车价最高，4车价最低
    payprice:'',//当前选中车价值
    goodsList:[],//商品列表数组
    isused: 1,//1为新车，2为二手车,
    phone:'',//当前手机号
    nearShop: [],//门店列表
    nearShopSel: {},//当前选择门店
    storepage:1,//当前门店列表页码
    storepagesize:6,//门店列表页面记录数
    storepagetotal: 1,//门店列表总页数
    storekeyword:'',//门店关键字
    storeflag: false,//门店列表显示隐藏标识
    storetitle:"上拉加载更多",//门店列表底部显示文字
    longitude:'',//经度
    latitude:'',//纬度
    page:1,//当前商品列表页码
    pagesize:6,//商品列表每页记录数
    pagetotal:1,//商品列表总页数
    title:"上拉加载更多",
    goodsid:'',//当前咨询商品id,
    city:'',//当前定位城市
    advTop:'',//列表头图
    heightarr:[],//筛选右边滚动各个标题距离顶部距离；
    lock:false,//筛选左侧标题点击加锁，防止触发滚动事件
      },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that=this;
    if (options.keyword){
         that.setData({
           keyword: options.keyword
         })
       }

    //定位获取门店列表   
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
        config.posthttp('api/v1/getNearShop', { longitude: that.data.longitude, latitude: that.data.latitude, page: that.data.storepage, page_size: that.data.storepagesize, keyword: that.data.storekeyword}, (res) => {
          that.setData({
            nearShop: res.data.nearShop,
            nearShopSel: res.data.nearShop[0],
            storepagetotal: res.data.total_page,
            storepage: that.data.storepage * 1 + 1,
            markers: [{
              latitude: res.data.nearShop[0].latitude,
              longitude: res.data.nearShop[0].longitude,
              title: res.data.nearShop[0].shop_name
            }],
          })
          if (that.data.storepage > res.data.total_page){
            that.setData({
              storetitle:"暂无更多门店"
            })
          }
        })

      },
    }) 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   const that=this;
    //筛选数据接口
    config.posthttp('api/v1/getSelParam', {is_used:1},(res)=>{
          that.setData({
            screen: res.data.set_param,
            cateList: res.data.cateList,
            payment: res.data.pay_param[1].values,
            monthpay: res.data.pay_param[0].values,
            paymentvalue: JSON.stringify(res.data.pay_param[1].values[0]) ,
            monthpayvalue: JSON.stringify(res.data.pay_param[0].values[0]),
            payprice: JSON.stringify(res.data.pay_param[2].values[0])
          })
      that.getGoodsList();
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     this.setData({
       phone:wx.getStorageSync('phone'),
       city:wx.getStorageSync('city')
     })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getGoodsListload();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //获取商品列表
  getGoodsList:function(){
    const that=this;
    that.setData({
      page:1
    })
    config.posthttp('api/v1/getGoodsList', {
      keyword: that.data.keyword,
      sort: that.data.sort,
      sel_attr: JSON.stringify(that.data.screenSelall),
      first_pay: that.data.paymentvalue,
      month_pay: that.data.monthpayvalue,
      pay_price: that.data.payprice,
      page: that.data.page,
      page_size: that.data.pagesize,
      cate_id: 0,
      is_used: that.data.isused
    }, (res) => {
      that.setData({
        advTop: res.data.advTop[0],
        goodsList: res.data.goodsList,
        page: that.data.page * 1 + 1,
        pagetotal: res.data.goodsPage.total_page,
        title: "上拉加载更多"
      })
      if (that.data.page > that.data.pagetotal){
        that.setData({
          title: "暂无更多车辆"
        })
      }
    })
  },

  //上拉加载商品列表
  getGoodsListload:function(){
    const that = this;
    if(that.data.page<=that.data.pagetotal){
      config.posthttp('api/v1/getGoodsList', {
        keyword: that.data.keyword,
        sort: that.data.sort,
        sel_attr: JSON.stringify(that.data.screenSelall),
        first_pay: that.data.paymentvalue,
        month_pay: that.data.monthpayvalue,
        pay_price: that.data.payprice,
        page: that.data.page,
        page_size: that.data.pagesize,
        cate_id: 0,
        is_used: that.data.isused
      }, (res) => {
        if (that.data.page == that.data.pagetotal){
          that.setData({
            title: "暂无更多车辆"
          })
        }
        that.setData({
          goodsList: that.data.goodsList.concat(res.data.goodsList),
          page: that.data.page * 1 + 1,
        })
      })
    }else{
      that.setData({
        title:"暂无更多车辆"
      })
    }
   
  },

  //咨询显示
  Consultation:function(e){
    const that=this;
    const goodsid=e.currentTarget.dataset.id;
    if(goodsid){
      that.setData({
        goodsid: goodsid
      })
    }
    that.setData({
      ConsultationFlag:'block'
    })
  },

  //咨询隐藏
  ConsultationClose:function(){
    const that = this;
    that.setData({
      ConsultationFlag: 'none'
    })
  },

  //顶部总分类切换效果
  classifySwitch: function (e) {
    const that = this;
    const id = e.currentTarget.dataset.id;
    if(that.data.classify!=id){
      that.setData({
        classify: id
      })
    }else{
      that.setData({
        classify: ''
      })
    }
    if (id==5){
      let heightarr = [];
      for (let i = 0; i < that.data.screen.length; i++) {
        wx.createSelectorQuery().select(`#scroll${i}`).fields({
          rect: true,
          scrollOffset: true
        }, function (res) {
          heightarr.push(res.top)
          if (i==that.data.screen.length-1){
            that.setData({
              heightarr:heightarr
            })
          }
        }).exec();
      }
    }
  },

  //关闭模态框
  brandclose:function(){
    this.setData({
      classify: ''
    })
  },
  //筛选左侧分类跳转
  screenClassify(e){
    const index=e.currentTarget.dataset.index;
    const id = e.currentTarget.dataset.id;
    this.setData({
      screenflag:index,
      toview: id,
      lock:true,
    })
  },

  //筛选点击效果事件
  checkboxClick(e) {
    const that = this;
    const idx = e.currentTarget.dataset.idx;
    const index = e.currentTarget.dataset.index;
    const data = that.data.screen;
    let sum = [];
    ((data)[idx].values)[index].checked ? ((data)[idx].values)[index].checked = false : ((data)[idx].values)[index].checked = true;
    for (let i = 0; i < data.length; i++) {
        for (let o = 0; o < data[i].values.length; o++) {
          if (data[i].values[o].checked && data[i].values[o].checked==true){
            sum = sum.concat(data[i].values[o]);
          }  
      }
    }
    that.setData({
      screen: data,
      screenSelstorage: sum
    })
  },

  //筛选点击取值事件
  checkboxChange(e) {
  },

  //筛选确认
  screenconfirm: function () {
    const data = this.data.screenSelstorage
    const rusult = this.data.screen
    for (let i = 0; i < rusult.length; i++) {
      for (let o = 0; o < rusult[i].values.length; o++) {
        rusult[i].values[o].checked=false;
      }
    }
     this.setData({
       screenSelall:data,
       classify:'',
       screen:rusult
     })
    this.getGoodsList();
  },
 

  //前往新车详情
  toCarDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/CarDetail/index?goodsid=' + id,
    })
  },

  //首付选择切换
  paymentSwitch:function(e){
  const id=e.currentTarget.dataset.id;  
  const index=e.currentTarget.dataset.index;
  let value = e.currentTarget.dataset.value;
  if(value=="不限"){
   value=''
  }
  this.setData({
    paymentflag:index,
    paymentname: value,
    paymentvalue:id,
    classify:''
  })
    this.getGoodsList();
  },

  //月供选择切换
 monthpaySwitch: function (e) {
    const id = e.currentTarget.dataset.id; 
    const index = e.currentTarget.dataset.index;
    let value = e.currentTarget.dataset.value;
    if (value == "不限") {
     value = ''
    }
    this.setData({
      monthpayflag:index,
      monthpayname:value,
      monthpayvalue:id,
      classify: ''
    })
   this.getGoodsList();
  },

  //排序切换
  sortSwitch:function(e){
     const id=e.currentTarget.dataset.id;
     this.setData({
       sort:id,
       classify: ''
     })
    this.getGoodsList();
  },

  //品牌选择
  brandclick:function(e){
    const keyword=e.currentTarget.dataset.keyword;
    this.setData({
      keyword:keyword,
      classify:''
    })
    this.getGoodsList();
  },

  //品牌，关键字，首付，月供已选分类清空
  mainclear:function(e){
    const that=this;
    const name=e.currentTarget.dataset.name;
    switch(name){
      case "brand":that.setData({keyword:''})
      break;
      case "payment": that.setData({ paymentname: '', paymentflag: 0, paymentvalue: JSON.stringify(that.data.payment[0])})
      break;
      case "month": that.setData({ monthpayname: '', monthpayflag: 0, monthpayvalue: JSON.stringify(that.data.monthpay[0])})
      break;
    }
    this.getGoodsList();
  },

  //筛选点击已选分类清除
  screenclear:function(e){
    const index=e.currentTarget.dataset.index;
    let data=this.data.screenSelall;
    data.splice(index,1)
    this.setData({
      screenSelall:data
    })
    this.getGoodsList();
  },

  //选择门店
  selectstore: function (e) {
    const that = this;
    const index = e.currentTarget.dataset.index;
    that.setData({
      nearShopSel: that.data.nearShop[index],
      storeflag: false,
    })
  },

  //门店列表打开关闭
  storeshowclose: function () {
    const that = this;
    if (that.data.storeflag) {
      that.setData({
        storeflag: false
      })
    } else {
      that.setData({
        storeflag: true
      })
    }
  },

  //上拉加载获取门店列表
  getNearShop:function(){
    const that = this;     
    if (that.data.storepage<=that.data.storepagetotal){
      config.posthttp('api/v1/getNearShop', { longitude: that.data.longitude, latitude: that.data.latitude, page: that.data.storepage, page_size: that.data.storepagesize, keyword: that.data.storekeyword }, (res) => {
        that.setData({
          nearShop: that.data.nearShop.concat(res.data.nearShop),
          storetitle:"上拉加载更多"
        })
      })
    }else{
      that.setData({
        storetitle: "暂无更多门店"
      })
    }
    that.setData({
      storepage: that.data.storepage * 1 + 1
    })
    
  },

//表单搜索获取门店列表
  getNearShopsearch(e){
    const that=this;
    that.setData({
      storekeyword: e.detail.value.replace(/\s+/g, ''),
      storepage:1
    })
    config.posthttp('api/v1/getNearShop', { longitude: that.data.longitude, latitude: that.data.latitude, page: that.data.storepage, page_size: that.data.storepagesize, keyword: that.data.storekeyword }, (res) => {
      that.setData({
        nearShop: res.data.nearShop,
        storetitle: "上拉加载更多",
        storepage: that.data.storepage * 1 + 1,
        storepagetotal: res.data.total_page
      })
      if (that.data.storepage > res.data.total_page) {
        that.setData({
          storetitle: "暂无更多门店"
        })
      }
    })
  },

  //预约咨询接口
  makeDatement:function(){
    const that=this;
    if ((/^1\d{10}$/.test(that.data.phone))){
      config.posthttp('api/v1/makeDatement', { goods_id: that.data.goodsid, shop_id: that.data.nearShopSel.id, mobile: that.data.phone, cate_id:0 }, (res) => {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        })
        setTimeout(()=>{
          that.setData({
            ConsultationFlag:'none',
          })
        },1500)
      })
    }else{
        wx.showToast({
          title: '手机号码有误',
          icon:"none"
        }) 
    }
  },

  //表单修改手机号码
  updatephone:function(e){
     const that=this;
     const data=e.detail.value;
     that.setData({
       phone:data,
     })
  },

  //首付自定义筛选
  slider1change:function(e){
    const that=this;
    if (e.detail.value==0){
      that.setData({ paymenttitle: "不限", paymentdiy: { id: 0, attr_id: 0, ext1: 0, ext2: e.detail.value } })
    }else{
      that.setData({
        paymenttitle: e.detail.value + '万以内',
        paymentdiy: {id:0,attr_id:0,ext1:0,ext2: e.detail.value}
      })
    } 
  },

  //首付自定义确定
  slider1define:function(){
    const that=this;
    if (that.data.paymentdiy.ext2 == 0 || !that.data.paymentdiy.ext2){
      that.setData({ paymentname: '', paymentvalue: JSON.stringify(that.data.payment[0]),classify:'' })
     }else{
      that.setData({ paymentname: that.data.paymenttitle, paymentvalue: JSON.stringify(that.data.paymentdiy), classify: '' })
     }
    this.getGoodsList(); 
  },

  //月供自定义筛选
  slider2change: function (e) {
    const that = this;
    if (e.detail.value == 0) {
      that.setData({ monthpaytitle: "不限", monthpaydiy: { id: 0, attr_id: 0, ext1: 0, ext2: e.detail.value } })
    }else{
      that.setData({
        monthpaytitle: e.detail.value + '元以内',
        monthpaydiy: { id: 0, attr_id: 0, ext1: 0, ext2: e.detail.value }
      })
    }
  },

  //月供自定义确认
  slider2define: function () {
    const that = this;
    if (that.data.monthpaydiy.ext2 == 0 || !that.data.monthpaydiy.ext2) {
      that.setData({ monthpayname: '', monthpayvalue: JSON.stringify(that.data.monthpay[0]), classify: '' })
    } else {
      that.setData({ monthpayname: that.data.monthpaytitle, monthpayvalue: JSON.stringify(that.data.monthpaydiy), classify: '' })
    }
    this.getGoodsList();
  },

  //新车头图链接
  toevery: function (e) {
    const that = this;
    const type = e.currentTarget.dataset.type;
    const value = e.currentTarget.dataset.value
    switch (type) {
      case 1:
        wx.navigateTo({
          url: `/pages/link/index?src=${value}`,
        });
        break;
      case 2:
        wx.navigateTo({
          url: `/pages/CarDetail/index?goodsid=${value}`,
        });
        break;
      case 4:
        wx.navigateTo({
          url: value,
        });
        break;
      case 5:
        wx.navigateTo({
          url: `/pages/noticeDetail/index?id=${value}`,
        });
        break;
      case 6:
        wx.navigateToMiniProgram({
          appId: value,
          path: '',
          extraData: {},
          envVersion: 'release',
          success(res) {
          }
        })
        break;
    }
  },

  //筛选滚动事件
  scrollbind:function(e){
    const that=this;
    let top = e.detail.scrollTop*1+41;
    for (let i=0; i < that.data.heightarr.length;i++){
      if (top<that.data.heightarr[i]&&!that.data.lock){
               that.setData({
                 screenflag:i-1,
               })
               break; 
        }
    }
    that.setData({
      lock:false,
    })
  }


  
  


})